﻿using System;
using System.Collections.Generic;
using System.Linq;

public class LockStepManager
{
    /// <summary>
    /// 上一帧时间
    /// </summary>
    private long lastTime;
    /// <summary>
    /// 当前时间
    /// </summary>
    private long currTime;
    /// <summary>
    /// 一帧的时间间隔
    /// </summary>
    private long timeInterval = 20;
    /// <summary>
    /// 是否开启
    /// </summary>
    public bool isStarted;
    /// <summary>
    /// 帧数
    /// </summary>
    public int turn = 0;
    /// <summary>
    /// 运行的房间
    /// </summary>
    public MatchRoom room;
    /// <summary>
    /// 所有操作 key：帧数 value：当前帧的所有操作
    /// </summary>
    public Dictionary<int, List<Opts>> allOpt = new Dictionary<int, List<Opts>>();
    /// <summary>
    /// 运行帧同步
    /// </summary>
    public void Run()
    {
        if (isStarted)
            return;
        isStarted = true;
        lastTime = (long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds;
        while (true)
        {
            currTime = (long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds;

            long time = currTime - lastTime;
            if (time > timeInterval)
            {
                lastTime = currTime;
                turn++;

                MsgLockStepBack msgLockStepBack = new MsgLockStepBack();
                msgLockStepBack.turn = turn;
                KeyValuePair<uint,int>[] playerUnsync0pt=room.playerUnsyncOpt.ToArray();
                foreach (var player in playerUnsync0pt)
                {
                    List<UnsyncOpts> unsyncOpts = new List<UnsyncOpts>();
                    //player.Value当前玩家同步到的帧数 turn表示服务器帧数 
                    //player.Value到turn之间表示当前客户端没有同步的帧数
                    if (player.Value < turn)
                    {
                        for (int i = player.Value; i < turn; i++)
                        {
                            UnsyncOpts unsyncOpt = new UnsyncOpts();
                            unsyncOpt.turn = i;
                            if (allOpt.ContainsKey(i))
                            {
                                unsyncOpt.opts = allOpt[i].ToArray();
                            }
                            unsyncOpts.Add(unsyncOpt);
                        }
                    }
                    msgLockStepBack.unsyncOpts = unsyncOpts.ToArray();
                    NetManager.SendTo(msgLockStepBack, player.Key);
                }
            }
        }
    }
}

